from PySide6.QtCore import Qt, Signal
from qfluentwidgets import SettingCard, FluentIconBase
from qfluentwidgetspro import RangeSlider
from app.common.config import cfg

class RangeSliderSettingCard(SettingCard):
    """ 双滑块范围选择设置卡片 """
    
    valueChanged = Signal(int, int)  # 发送最小值和最大值

    def __init__(self, icon: FluentIconBase, title: str, content: str, 
                 configItem, parent=None, minimum=0, maximum=100):
        """
        Parameters
        ----------
        icon: FluentIconBase
            卡片图标
        title: str
            卡片标题
        content: str
            卡片描述文本
        configItem: ConfigItem
            配置项(需要能够存储两个值)
        parent: QWidget
            父级窗口
        minimum: int
            滑块最小值
        maximum: int
            滑块最大值
        """
        super().__init__(icon, title, content, parent)
        self.configItem = configItem
        
        # 创建范围滑块控件
        self.rangeSlider = RangeSlider(self)
        self.rangeSlider.setOrientation(Qt.Horizontal)  # 设置为水平方向
        self.rangeSlider.setMinimum(minimum)
        self.rangeSlider.setMaximum(maximum)
        
        # 设置初始值
        default_values = self.configItem.value
        if isinstance(default_values, (list, tuple)) and len(default_values) == 2:
            self.rangeSlider.setRangeStart(default_values[0])
            self.rangeSlider.setRangeEnd(default_values[1])
        else:
            self.rangeSlider.setRangeStart(minimum)
            self.rangeSlider.setRangeEnd(maximum)
            
        self.rangeSlider.setMinimumWidth(200)
        
        # 将范围滑块添加到右侧
        self.hBoxLayout.addWidget(self.rangeSlider, 0, Qt.AlignRight)
        
        # 连接信号
        self.rangeSlider.rangeStartChanged.connect(self._onValueChanged)
        self.rangeSlider.rangeEndChanged.connect(self._onValueChanged)

    def _onValueChanged(self):
        """ 值改变时的处理 """
        start = self.rangeSlider.getRangeStart()
        end = self.rangeSlider.getRangeEnd()
        self.configItem.value = [start, end]
        cfg.save()
        self.valueChanged.emit(start, end)

    def getValues(self) -> tuple:
        """ 获取当前的范围值
        
        Returns
        -------
        tuple:
            返回(最小值, 最大值)
        """
        return (self.rangeSlider.getRangeStart(), self.rangeSlider.getRangeEnd())

    def setValues(self, start: int, end: int):
        """ 设置范围值
        
        Parameters
        ----------
        start: int
            起始值
        end: int
            结束值
        """
        self.rangeSlider.setRangeStart(start)
        self.rangeSlider.setRangeEnd(end) 